document.addEventListener('DOMContentLoaded', function () {
    const deleteButtons = document.querySelectorAll('.delete-btn');
    const editButtons = document.querySelectorAll('.edit-btn');
    const form = document.getElementById('course-search-form');
    const tbody = document.querySelector('.course-table tbody');
    const token = localStorage.getItem('access_token');
    // 渲染课程列表
    function fetchCourses() {
    const courseName = document.getElementById('course-name').value;
    const creditsMin = document.getElementById('credits-min').value;
    const creditsMax = document.getElementById('credits-max').value;
    const courseType = document.getElementById('course-type').value;

    const params = {
        course_name: courseName,
        credits_min: creditsMin,
        credits_max: creditsMax,
        course_type: courseType
    };

    const queryString = new URLSearchParams(params).toString();
    
    fetch(`/api/course_manage/?${queryString}`, {
        method: 'GET',
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            'Authorization': `Bearer ${token}`,
        }
    })
    .then(response => response.json())
    .then(data => {
        renderCourseTable(data.data || []);
    })
    .catch(error => {
        tbody.innerHTML = '<tr><td colspan="10">查询失败</td></tr>';
    });
}



    // 渲染课程表格
    function renderCourseTable(courseList) {
        tbody.innerHTML = '';
        if (courseList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="10">暂无课程</td></tr>';
            return;
        }
        courseList.forEach((course, idx) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${idx + 1}</td>
                <td>${course.course_no}</td>
                <td>
                    ${course.course_name}
                    ${course.course_textbook_pic ? `<img src="data:image/png;base64,${course.course_textbook_pic}" alt="教材封面" class="course-image">` : ''}
                </td>
                <td>${course.course_hours}</td>
                <td>${course.course_point}</td>
                <td>${course.type_name}</td>
                <td>${course.course_status}</td>
                <td>${course.course_reqs}</td>
                <td>${course.course_memo}</td>
                <td>
                    <button class="edit-btn" data-id="${course.course_no}">修改</button>
                    <button class="delete-btn" data-id="${course.course_no}">删除</button>
                </td>
            `;
            tbody.appendChild(tr);
        });
        bindEditButtons();
        bindDeleteButtons();
    }

    // 绑定删除按钮事件
    function bindDeleteButtons() {
        const deleteButtons = document.querySelectorAll('.delete-btn');
        deleteButtons.forEach(button => {
            button.addEventListener('click', function () {
                const courseId = button.getAttribute('data-id');
                if (confirm('确定要删除该课程吗？')) {
                    fetch(`/api/course_manage/${courseId}/`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                            'Authorization': `Bearer ${token}`,
                        }
                    })
                    .then(response => {
                        if (response.ok) {
                            alert('课程删除成功！');
                            fetchCourses();
                        } else {
                            throw new Error('删除失败');
                        }
                    })
                    .catch(error => {
                        alert('删除失败，请稍后再试！');
                    });
                }
            });
        });
    }

    // 绑定修改按钮事件
    function bindEditButtons() {
        const editButtons = document.querySelectorAll('.edit-btn');
        editButtons.forEach(button => {
            button.addEventListener('click', function () {
                const courseId = button.getAttribute('data-id');
                window.location.href = `/edit-course/${courseId}/`;
            });
        });
    }

    // 查询表单提交事件
    form.addEventListener('submit', function (event) {
        event.preventDefault();
        const creditsMin = document.getElementById('credits-min').value;
        const creditsMax = document.getElementById('credits-max').value;
        if ((creditsMin && isNaN(parseFloat(creditsMin))) || (creditsMax && isNaN(parseFloat(creditsMax)))) {
            alert('请输入有效的学分范围（数字或小数）');
            return;
        }
        fetchCourses();
    });

    // 页面加载时自动查询
    fetchCourses();
});